package com.ruslan.magaz.web;

import java.util.List;

import javax.ws.rs.DELETE;
import javax.ws.rs.GET;
import javax.ws.rs.POST;
import javax.ws.rs.PUT;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.dao.EmptyResultDataAccessException;
import org.springframework.data.domain.Page;
import org.springframework.http.HttpStatus;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.ResponseStatus;

import com.ruslan.magaz.entity.User;
import com.ruslan.magaz.service.InfoService;
import com.ruslan.magaz.service.UserService;

@Controller("userController")
@RequestMapping("/user")
public class UserController {
	private static final Integer MAX_PER_PAGE = 25;

	@Autowired
	private UserService userService;
	@Autowired
	private InfoService infoService;

	@GET
	@RequestMapping(value = "/", method = RequestMethod.GET, produces = { "application/json" })
	@ResponseBody
	public Page<User> getUsers(
			@RequestParam(value = "page", defaultValue = "1") Integer page) {

		int maxResults = MAX_PER_PAGE;

		return userService.getUsers(page - 1, maxResults);
	}

	@POST
	@RequestMapping(value = "/letter", method = RequestMethod.POST, produces = { "application/json" })
	@ResponseBody
	public Page<User> getUsers(@RequestBody LetterDTO letterDTO) {
		String letter = letterDTO.getLetter();
		int page = letterDTO.getPage();
		return userService.getUsersForLetter(letter, page - 1, MAX_PER_PAGE);
	}

	@RequestMapping(value = "/letters", method = RequestMethod.GET, produces = { "application/json; charset=UTF-8" })
	@ResponseBody
	public List<String> getFirstLetters() {
		return userService.getFirstLetters();
	}

	@DELETE
	@RequestMapping(value = "/delete/{userId}", method = RequestMethod.DELETE, produces = { "application/json" })
	@ResponseBody
	public void deleteCategory(
			@PathVariable(value = "userId") Integer userId) {
		userService.removeUser(userId);
	}

	@PUT
	@RequestMapping(value = "/create", method = RequestMethod.PUT, produces = { "application/json" }, consumes = { "application/json" })
	@ResponseBody
	public void createProduct(@RequestBody UserDTO userDTO) throws IllegalFormatException, AlreadyExistsException {
		if (userDTO.getFirstName().trim().isEmpty()
				|| userDTO.getLastName().trim().isEmpty()) {
			throw new IllegalFormatException("Error");
		}
		
		if (userService.countSameUser(userDTO.getFirstName(),
				userDTO.getMiddleName(), userDTO.getLastName()) > 0) {
			throw new AlreadyExistsException("Same user already exists!");
		}
		
		User user = new User();
		user.setFirstName(userDTO.getFirstName());
		user.setMiddleName(userDTO.getMiddleName());
		user.setLastName(userDTO.getLastName());
		userService.addUser(user);
	}

	@POST
	@RequestMapping(value = "/update", method = RequestMethod.POST, produces = { "application/json" }, consumes = { "application/json" })
	@ResponseBody
	public void updateUser(@RequestBody UserDTO userDTO) throws IllegalFormatException, AlreadyExistsException {
		if (userDTO.getFirstName().trim().isEmpty()
				|| userDTO.getLastName().trim().isEmpty()) {
			throw new IllegalFormatException("Error");
		}
		
		if (userService.countIdenticalUsers(userDTO.getId(), userDTO.getFirstName(),
				userDTO.getMiddleName(), userDTO.getLastName()) > 0) {
			throw new AlreadyExistsException("Same user already exists!");
		}
		
		User user = new User();
		user.setId(userDTO.getId());
		user.setFirstName(userDTO.getFirstName());
		user.setMiddleName(userDTO.getMiddleName());
		user.setLastName(userDTO.getLastName());
		userService.updateUser(user);

	}
	
    @ExceptionHandler(AlreadyExistsException.class)
    @ResponseStatus(value=HttpStatus.CONFLICT)
    @ResponseBody
    public ContactsResponse handleAlreadyExistsException(AlreadyExistsException ex) {
 
        return new ContactsResponse("ERROR", ex.getMessage());
   }
    
    @ExceptionHandler(IllegalFormatException.class)
    @ResponseStatus(value=HttpStatus.NOT_ACCEPTABLE)
    @ResponseBody
    public ContactsResponse handleIllegalFormatException(IllegalFormatException ex) {
 
        return new ContactsResponse("ERROR", ex.getMessage());
   }
    @ExceptionHandler(EmptyResultDataAccessException.class)
    @ResponseStatus(value=HttpStatus.NOT_FOUND)
    @ResponseBody
    public ContactsResponse handleEmptyResultDataAccessException(EmptyResultDataAccessException ex) {
 
        return new ContactsResponse("ERROR", ex.getMessage());
   }

}
